package org.zoomdev.zoom.lock.modules;

import org.zoomdev.zoom.lock.Executor;
import org.zoomdev.zoom.lock.LockExecutor;
import org.zoomdev.zoom.lock.LockFactory;

import java.util.concurrent.locks.Lock;

class DefaultLockExecutor implements LockExecutor {

    private final LockFactory<Lock> lockFactory;

    public DefaultLockExecutor(LockFactory<Lock> lockFactory) {
        this.lockFactory = lockFactory;
    }

    @Override
    public Object execute(String key, Executor executor) throws Throwable {
        Lock lock = lockFactory.fetch(key);
        try {
            lock.lock();
            return executor.execute();
        } finally {
            lock.unlock();
        }
    }
}
